package com.itheima.health.service.impl;

import com.itheima.health.common.MessageConst;
import com.itheima.health.dao.AppointmentOrderDao;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.Order;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.AppointmentOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 预约实现类
 * @author snowsee
 * @date 2023/4/27 11:57
 */
@Service
public class AppointmentOrderServiceImpl implements AppointmentOrderService {

    @Autowired
    private AppointmentOrderDao appointmentOrderDao;
    /**
     * 根据电话号查询会员信息
     *
     * @param member
     * @return
     */
    @Override
    @Transactional
    public Member saveByPhoneNumber(Member member) {
        Member pojo = appointmentOrderDao.selectByPhoneNumber(member.getPhoneNumber());
        // 有会员就更新 没有就创建并返回主键
        if (pojo == null) {
            member.setRegTime(new java.sql.Date(new Date().getTime()));
            this.appointmentOrderDao.insertMember(member);
        } else {
            member.setId(pojo.getId());
            this.appointmentOrderDao.updateMember(member);
        }
        return member;
    }

    /**
     * 验证预约是否已满
     *
     * @param orderDate
     * @return
     */
    @Override
    public void getOrderSettingByOrderDate(String orderDate) {
        OrderSetting orderSetting = this.appointmentOrderDao.selectOrderSettingByOrderDate(orderDate);
        // 空的说明没有设置当前日期的预约
        if (orderSetting == null)
            throw new BusinessRuntimeException(MessageConst.SELECTED_DATE_CANNOT_ORDER);
        // 查看当前日期预约是否已满
        if (orderDate.equals(orderSetting.getOrderDate().toString())){
            if (orderSetting.getReservations() >= orderSetting.getNumber())
                throw new BusinessRuntimeException(MessageConst.ORDER_FULL);
        }
    }

    /**
     * 存入预约信息&设置表+1
     */
    @Override
    @Transactional
    public void saveOrderAndSetting(Order order) {
        // 查询是否有重复预约  同一个人同一天同一个套餐
        long count = this.appointmentOrderDao.countByMemberAndDateAndSetMeal(order.getMemberId(),order.getOrderDate(),order.getSetmealId());
        if(count > 0){
            throw new BusinessRuntimeException(MessageConst.HAS_ORDERED);
        }
        this.appointmentOrderDao.insertOrder(order);
        this.appointmentOrderDao.updateOrderSetting(order.getOrderDate());
    }
}
